package com.tony.business.controller;

import com.tony.domain.bo.JsonResult;
import com.tony.domain.enumerate.ErrorEnum;
import com.tony.util.properties.UploadFileProperties;
import com.tony.util.utils.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author x
 */
@Api(tags = "上传文件相关")
@RestController
@Validated
@RequestMapping("/upload")
public class UploadFileController {

    @Autowired
    private UploadFileProperties properties;

    private static final char POINT = '.';

    @PostMapping("/uploadFile")
    @ApiOperation(value = "上传文件", httpMethod = "POST")
    public JsonResult<String> uploadFile(@RequestParam("file") @NotNull MultipartFile file){

        try {
            return new JsonResult<>(UploadUtil.uploadFile(file.getInputStream(),getSuffix(file),properties));
        } catch (IOException e) {
            e.printStackTrace();
            return new JsonResult<>(ErrorEnum._100500);
        }
    }

    @PostMapping(value = "/uploadFiles")
    @ApiOperation(value = "批量上传文件", httpMethod = "POST")
    public JsonResult<List<String>> uploadFiles(@RequestParam("files") @NotNull MultipartFile[] files){
        try {
            List<String> list = new ArrayList<>(files.length);
            for (MultipartFile file : files) {
                list.add(UploadUtil.uploadFile(file.getInputStream(),getSuffix(file),properties));
            }
            return new JsonResult<>(list);
        } catch (IOException e) {
            e.printStackTrace();
            return new JsonResult<>(ErrorEnum._100500);
        }
    }

    /**
     * 获取上传文件后缀
     * @param file 上传文件
     * @return 后缀名
     */
    private String getSuffix(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String suffix = "";
        assert originalFilename != null;
        if(originalFilename.lastIndexOf(POINT) > 0){
            suffix = originalFilename.substring(originalFilename.lastIndexOf(POINT));
        }
        return suffix;
    }
}
